# -*- coding: utf-8 -*-
# @Time    : 2022/7/20 10:24
# @Author  : Yanfeng
# @Email   : sxyanfeng2014@163.com
# @File    : __init__.py.py
# @Software: PyCharm


import time
from PIL import Image
import ddddocr
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from Common.dir_config import ConfigHandler
from Common.logger import Logger



class BasePage:

    def __init__(self,driver:WebDriver):
        self.driver = driver  #初始化drivr

    #智能获取验证码
    def get_code(self,id):
        # 获取验证码图片
        t = time.time()
        picture_name1 = ConfigHandler.screenshot_dir + '\\' + str(t) + '.png'

        self.driver.save_screenshot(picture_name1)
        loc = (By.ID, id)
        ce = self.get_emement(loc,"根据图片id查找元素")

        left = ce.location['x']
        top = ce.location['y']
        right = ce.size['width'] + left
        height = ce.size['height'] + top

        dpr = self.driver.execute_script('return window.devicePixelRatio')
        # print(dpr)
        im = Image.open(picture_name1)
        img = im.crop((left * dpr, top * dpr, right * dpr, height * dpr))

        t = time.time()

        picture_name2 = ConfigHandler.screenshot_dir + '\\' + str(t) + '.png'
        img.save(picture_name2)  # 这里就是截取到的验证码图片
        # # print("picture_name2" + ":" + picture_name2)

        ocr = ddddocr.DdddOcr()
        with open(picture_name2, "rb") as f:
            image = f.read()
        res = ocr.classification(image)
        return res

    #等待元素visibility_of_element_located
    def wait_ele_visible(self,loc,img_name,timeout=20,poll_fre=0.5):
        """
        :param loc:
        :param img_name:
        :param timeout:
        :param poll_fre:
        :return:
        """
        try:
            # WebDriverWait(self.driver,timeout,poll_frequency=poll_fre).until(EC.visibility_of_element_located(loc))
            WebDriverWait(self.driver, timeout, poll_frequency=poll_fre).until(EC.presence_of_element_located(loc))

        except:
            self.save_page_shot()
            Logger.exception("等待元素{}可见失败：".format(loc))
            raise

    #查找元素
    def get_emement(self,loc,img_name):

        self.wait_ele_visible(loc,img_name)

        try:
            ele = self.driver.find_element(*loc)
        except:
            self.save_page_shot()
            Logger.exception("查找元素{}失败".format(loc))
            raise
        else:
            return ele

    #查找元素们
    def get_emements(self,loc,img_name):

        self.wait_ele_visible(loc, img_name)

        try:
            eles = self.driver.find_elements(*loc)
        except:
            self.save_page_shot()
            Logger.exception("查找元素{}失败".format(loc))
            raise
        else:
            return eles

    #元素存在
    def  wait_page_contain_element(self):
        pass

    #等待元素可点击
    def wait_ele_clickable(self,loc,img_name,timeout=20,poll_fre=0.5):
        try:
            WebDriverWait(self.driver, timeout, poll_frequency=poll_fre).until(EC.element_to_be_clickable(loc))
        except:
            self.save_page_shot()
            Logger.exception("元素{}不可点击".format(loc))
            raise
    #js执行
    #上传（windows）
    #页面滚动条滚动到元素底部，参数是元素loc
    def scroll_ele(self,loc,img_name):
        ele = self.get_emement(loc,img_name)
        try:
            self.driver.execute_script("arguments[0].scrollIntoView(false)",ele)
        except:
            self.save_page_shot()
            Logger.exception("滚动到元素{}底部失败".format(loc))
            raise

    def save_page_shot(self):
        """

        :param img_name: 页面名称_页面行为
        :return:
        """
        #将图片存储到Outputs的screenshots下，图片命名：页面名称_页面行为_时间.png
        now = time.strftime("%Y-%m-%d %H_%M_%S")
        screenshot_path = ConfigHandler.screenshot_dir+"/{}.png".format(now)
        self.driver.save_screenshot(screenshot_path)
        Logger.info("页面图片保存在：{}".format(screenshot_path))












if __name__ == '__main__':
    from  selenium import webdriver
    driver = webdriver.Chrome(r"F:\python\chromedriver.exe")
    driver.get("http://test.zhcxkj.com//Manager/index.aspx")
    driver.maximize_window()
    ba = BasePage(driver)


